package cn.house.rent.service.impl;

import cn.house.rent.entity.User;
import cn.house.rent.mapper.UserMapper;
import cn.house.rent.service.UserService;
import cn.house.rent.utils.Captcha;
import cn.house.rent.utils.Result;
import cn.house.rent.vo.NodeVo;
import cn.house.rent.vo.UserVo;
import cn.hutool.json.JSONUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.List;

@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private UserMapper userMapper;

    //登录
    @Override
    public Result login(UserVo userVo, HttpServletResponse resp, HttpSession session) {
        boolean captchaCheck = session.getAttribute("captcha").equals(userVo.getCaptcha());
        Result res = new Result();
        System.out.println("userVo = " + userVo);
        if (captchaCheck) {
            User login = userMapper.login(userVo);
            //用户名或密码错误
            if (login == null) {
                res.setCode(500);
                res.setMsg("用户名或密码错误！");
            } else {
                Cookie ck1 = new Cookie("username", login.getUserName());
                Cookie ck2 = new Cookie("password", login.getPassword());
                Cookie ck3 = new Cookie("remember", userVo.getRemember());
                if ("true".equals(userVo.getRemember())) {
                    //设置cookie的存活时间  一周免登录
                    ck1.setMaxAge(604800);
                    ck2.setMaxAge(604800);
                    ck3.setMaxAge(604800);
                }else {
                    //设置cookie的存活时间
                    ck1.setMaxAge(0);  // 立即删除
                    ck2.setMaxAge(0);
                    ck3.setMaxAge(0);
                }
                ck1.setPath("/");
                ck2.setPath("/");
                ck3.setPath("/");
                //将ck1 和ck2 响应到前端
                resp.addCookie(ck1);
                resp.addCookie(ck2);
                resp.addCookie(ck3);
                res.setCode(0);
                res.setMsg("登陆成功！");
                res.setData(login);
                session.setAttribute("user", login);
                session.setAttribute("username", login.getUserName());
            }
        } else {
            res.setMsg("验证码错误！");
            res.setCode(500);
        }
        return res;
    }

    //用户名重复检测
    @Override
    public Result registerCheck(String userName) {
        User check = userMapper.registerCheck(userName);
        Result result = new Result();
        if (check == null) {
            result.setCode(0);
            result.setMsg("该账户可用！");
            result.setData(userName);
        } else {
            result.setCode(500);
            result.setMsg("该账户已被注册！");
            result.setData(userName);
        }
        return result;
    }

    //    邮箱重复检测
    @Override
    public Result emailCheck(String email) {
        User check = userMapper.emailCheck(email);
        Result result = new Result();
        if (check == null) {
            result.setCode(0);
            result.setMsg("该邮箱可用！");
            result.setData(email);
        } else {
            result.setCode(500);
            result.setMsg("该邮箱已被注册！");
            result.setData(email);
        }
        return result;
    }

    @Override
    public Result register(User user, @RequestParam("captcha") String captcha, HttpSession session) {
        boolean captchaCheck = session.getAttribute("captcha").equals(captcha);
        Result res = new Result();
        if (captchaCheck) {
            int i = userMapper.register(user);
            res.setCode(i > 0 ? 0 : 500);
            res.setMsg(i > 0 ? "注册成功！" : "注册失败！");

        } else {
            res.setMsg("验证码错误！");
            res.setCode(500);
        }
        return res;

    }

    //查询菜单
    @Override
    public Result selectMenu(User user) {
        //查询该用户对象所有权限id
        List<Integer> nodeIds = userMapper.selectByRoleIdNodeId(user.getRoleId());
        //查询该用户对象所有权限
        List<NodeVo> nodeVos = userMapper.selectByNodeIds(nodeIds);
        Result result = Result.builder().code(0).msg("加载成功").data(nodeVos).build();
        return result;
    }

    //根据条件查询查询用户信息
    @Override
    public Result selectUserInfos(UserVo userVo) {
        PageHelper.startPage(userVo.getPage(), userVo.getLimit());
        List<UserVo> userInfos = userMapper.selectUserInfos(userVo);
        PageInfo<UserVo> page = new PageInfo<>(userInfos);
        if (userInfos != null) {
            return Result.builder().code(0).msg("查询成功").data(userInfos).count(page.getTotal()).build();
        } else {
            return Result.builder().code(500).msg("查询失败").build();
        }
    }


    //根据用户id更改用户信息
    @Override
    public Result updateUser(User user) {
        int line = userMapper.updateUser(user);
        if (line > 0) {
            User usr = userMapper.selectById(user.getUserId());
            return Result.builder().code(0).msg("更新成功！").data(usr).build();
        } else {
            return Result.builder().code(500).msg("更新失败！").build();
        }
    }

    //根据id修改用户密码
    @Override
    public Result updatePwd(UserVo userVo, User user) {
        if (user.getPassword().equals(userVo.getPassword())) {
            userVo.setUserId(user.getUserId());
            int line = userMapper.updatePwd(userVo);
            if (line > 0) {
                return Result.builder().code(0).msg("修改成功！").build();
            } else {
                return Result.builder().code(500).msg("修改失败！").build();
            }
        } else {
            return Result.builder().code(500).msg("密码错误，无法修改！").build();
        }
    }

    //根据id修改用户头像
    @Override
    public int updateUserImg(User user) {
        return userMapper.updateUserImg(user);
    }

    //用户管理  添加用户
    @Override
    public Result addUser(UserVo userVo) {
        userVo.setPassword("123456");
        int line = userMapper.addUser(userVo);
        if (line > 0) {
            return Result.builder().code(0).msg("添加成功！").build();
        } else {
            return Result.builder().code(500).msg("添加失败！").build();
        }
    }

    //用户管理  重置用户密码
    @Override
    public Result resetUser(UserVo userVo) {
        userVo.setNewpassword("123456");
        int line = userMapper.updatePwd(userVo);
        if (line > 0) {
            return Result.builder().code(0).msg("重置密码成功！").build();
        } else {
            return Result.builder().code(500).msg("重置密码失败！").build();
        }
    }

    //用户管理  删除用户  批量删除用户
    @Override
    public Result delUser(UserVo userVo) {
        int line;
        if (userVo.getIds() != null && userVo.getIds() != "") {
            line = userMapper.delUsers(userVo.getIds());
        } else {
            line = userMapper.delUser(userVo.getId());
        }
        if (line > 0) {
            return Result.builder().code(0).msg("删除成功！").build();
        } else {
            return Result.builder().code(500).msg("删除失败！").build();
        }
    }

    //找回密码
    @Override
    public Result forget(UserVo userVo) {
        int line = userMapper.forget(userVo);
        if (line > 0) {
            return Result.builder().code(0).msg("找回密码成功").build();
        } else {
            return Result.builder().code(500).msg("该邮箱未绑定账号").build();
        }
    }

}
